<?php

include "../../lib/start.php";

check_session();
check_permission(ADM_PERM);

if(!isset($_REQUEST['offset']))
    $offset = 0;
else
    $offset = $_REQUEST['offset'];

$limit = 15;

// indica se attivati i filtri
$filtered = false;
$query = "";

$sel_user = "SELECT genitori.id_genitore, genitori.nome, genitori.cognome, alunni.nome AS al_name, alunni.cognome AS al_lname, alunni.classe AS classe FROM genitori, alunni, genitori_figli WHERE alunni.id_alunno = genitori_figli.id_alunno AND genitori_figli.id_genitore = genitori.id_genitore AND alunni.attivo = 1 ";
if(isset($_REQUEST['sezione']) && isset($_REQUEST['classe'])){
	$filtered = true;
	$query .= "&classe=".$_REQUEST['classe']."&sezione=".$_REQUEST['sezione'];
	$sel_user .= " AND classe LIKE '".$_REQUEST['classe'].$_REQUEST['sezione']."' ";
}
else if(isset($_REQUEST['sezione'])){
	$filtered = true;
	$query .= "&sezione=".$_REQUEST['sezione'];
	$sel_user .= " AND classe LIKE '%".$_REQUEST['sezione']."' ";
}
else if(isset($_REQUEST['classe'])){
	$filtered = true;
	$query .= "&classe=".$_REQUEST['classe'];
	$sel_user .= " AND classe LIKE '".$_REQUEST['classe']."%' ";
}
if(isset($_REQUEST['nome']) && (trim($_REQUEST['nome']) != "")){
	$filtered = true;
	$query .= "&nome=".$_REQUEST['nome'];
	$sel_user .= " AND (genitori.nome LIKE '%".strtoupper($_REQUEST['nome'])."%' OR genitori.cognome LIKE '%".strtoupper($_REQUEST['nome'])."%') ";
}
if(isset($_REQUEST['aname']) && (trim($_REQUEST['aname']) != "")){
	$filtered = true;
	$query .= "&aname=".$_REQUEST['aname'];
	$sel_user .= " AND (alunni.nome LIKE '%".strtoupper($_REQUEST['aname'])."%' OR alunni.cognome LIKE '%".strtoupper($_REQUEST['aname'])."%') ";
}

if(isset($_REQUEST['order']) && ($_REQUEST['order'] == "class")){
	$sel_user .= "ORDER BY classe, cognome, nome";
	$new_order = "nome";
	$current_order = "class";
	$button_label = "Ordina per nome";
}
else{
	//$sel_user .= "ORDER BY cognome, nome, classe";
	$new_order = "class";
	$current_order = "nome";
	$button_label = "Ordina per classe";
}
$query .= " ORDER BY genitori.cognome, genitori.nome, alunni.cognome, alunni.nome ";

if(!isset($_GET['second'])){
	try{
    	$res_user = $db->executeQuery($sel_user);
	} catch (MySQLException $ex){
		$ex->redirect();
	}
    //print $sel_links;
    $count = $res_user->num_rows;
    $_SESSION['count_genitori'] = $count;
}
else{
    $sel_user .= " LIMIT $limit OFFSET $offset";
	try{
    	$res_user = $db->executeQuery($sel_user);
	} catch (MySQLException $ex){
		$ex->redirect();
	}
}
//print $sel_user;

if($offset == 0)
    $page = 1;
else
    $page = ($offset / $limit) + 1;

$pagine = ceil($_SESSION['count_genitori'] / $limit);
if($pagine < 1)
    $pagine = 1;

// dati per la paginazione (navigate.php)
$colspan = 3;
$link = basename($_SERVER['PHP_SELF']);
$count_name = "count_genitori";
$row_class = "admin_row";

include "genitori.html.php";

?>